<template>
  <div class="p-6">
    <div class="flex items-center space-x-4">
      <a-button type="primary" v-for="(app, index) in apps" :key="index" @click="openApp(app)">
        打开 {{ app.name }}
      </a-button>
    </div>
    <div class="mt-60 flex flex-col justify-center items-center">
      <a-form :model="formState" @finish="handleFinish" style="width: 500px">
        <a-form-item name="userAccount">
          <a-input v-model:value="formState.userAccount" placeholder="Username">
            <template #prefix>
              <UserOutlined style="color: rgba(0, 0, 0, 0.25)" />
            </template>
          </a-input>
        </a-form-item>
        <a-form-item name="userPassword">
          <a-input-password
            v-model:value="formState.userPassword"
            type="password"
            placeholder="Password"
          >
            <template #prefix>
              <LockOutlined style="color: rgba(0, 0, 0, 0.25)" />
            </template>
          </a-input-password>
        </a-form-item>
        <a-form-item>
          <a-button
            type="primary"
            html-type="submit"
            :loading="loginLoading"
            :disabled="formState.user === '' || formState.password === ''"
          >
            Log in
          </a-button>
          <a-button class="ml-2" @click="resetUser">重置登录状态</a-button>
        </a-form-item>
      </a-form>

      <p>token信息：</p>
      <a-typography-text keyboard>{{ tokenDataStr }}</a-typography-text>
      <p>用户信息：</p>
      <a-typography-text keyboard>{{ getUserInfoDataStr }}</a-typography-text>
    </div>
  </div>
</template>

<script setup>
  import { ref, reactive, computed, onMounted } from 'vue';
  import { ipcRenderer } from 'electron';
  import { cloneDeep } from 'lodash-es';
  import { UserOutlined, LockOutlined } from '@ant-design/icons-vue';
  import { loginApi, getUserInfoApi } from '@/api';
  import { message } from 'ant-design-vue';
  import { storeLib } from '@/utils/src/store';

  const apps = ref([
    {
      name: '应用--webpack-test-app',
      loadUrl: 'http://localhost:8080/',
      // loadUrl: 'https://www.electronjs.org/zh/docs/latest/api/web-contents#contentsexecutejavascriptinisolatedworldworldid-scripts-usergesture/',
      id: 0,
    },
    {
      name: '应用--vite-test-app',
      loadUrl: 'http://localhost:5173/',
      id: 1,
    },
  ]);

  const tokenDataStr = computed(() => {
    const tokenData = storeLib.get('tokenData');
    if (tokenData) {
      return JSON.stringify(tokenData, null, 2);
    }
    return 'null';
  });

  const getUserInfoDataStr = computed(() => {
    const getUserInfoData = storeLib.get('getUserInfoData');
    if (getUserInfoData) {
      return JSON.stringify(getUserInfoData, null, 2);
    }
    return 'null';
  });

  onMounted(() => {
    getUserInfoApi().catch(() => {
      storeLib.set('getUserInfoData', null);
    });
  });

  function resetUser() {
    storeLib.set('getUserInfoData', null);
    storeLib.set('tokenData', null);
  }

  function openApp(appInfo) {
    ipcRenderer.send('sendMain__workbenchApplicationWindow_sendAppInfo', cloneDeep(appInfo));
  }

  const loginLoading = ref(false);

  const formState = reactive({
    userAccount: '17606442088',
    userPassword: 'ms123456',
  });

  function saveTokenData(res) {
    storeLib.set('tokenData', res);
  }

  function handleFinish(value) {
    loginLoading.value = true;
    loginApi({
      username: value.userAccount,
      password: value.userPassword,
      grant_type: 'password',
    })
      .then(res => {
        saveTokenData(res);
        return getUserInfo(res);
      })
      .catch(error => {
        if (error?.code === 500) {
          message.error(error.msg);
          return;
        }
        message.error('登录失败');
      })
      .finally(() => {
        loginLoading.value = false;
      });
  }

  function getUserInfo() {
    return getUserInfoApi()
      .then(res => {
        if (res.code !== 200) {
          message.error('获取用户信息失败');
          return;
        }
        storeLib.set('getUserInfoData', res.data);
      })
      .catch(error => {
        console.log(error);
        message.error('获取用户信息失败');
        return Promise.reject(error);
      });
  }
</script>
